/// <reference path="../Resources/js/jquery/jquery.debug.js" />
/// <reference path="../Controls/Items/MItem.js" />
/// <reference name="MicrosoftAjax.debug.js" />

Type.registerNamespace("BM");

// AddButtons object

BM.AddButtons = function(element) {
    BM.AddButtons.initializeBase(this, [element]);
}

BM.AddButtons.CssClass = "MForm-BtnC";

BM.AddButtons.prototype = {
    getItem: function() {
        return this.item;
    },

    setItem: function(item) {
        this.item = item;
    },

    clear: function(item) {
        this.setItem(item);
        $(this.get_element()).children().remove();
    },

    get_depth: function() {
        return this.depth;
    },

    set_depth: function(value) {
        this.depth = value;
    },

    get_countEmptyContainers: function() {
        return this.countEmptyContainers;
    },

    set_countEmptyContainers: function(value) {
        this.countEmptyContainers = value;
    },

    update: function(item, clickEvent) {
        if (item == this.getItem()) return;
        this.clear(item);
        this.appendAll(item);
    },

    appendAll: function(item) {
        var depth = 0;
        while (depth < this.get_depth()) {
            if (!item) {
                break;
            }
            if (this.append(item)) {
                depth++;
            }
            item = item.getParentItem();
        }
    },

    append: function(item) {
        var buttons = $(item.node).children('.' + BM.AddButtons.CssClass).children().clone();
        for (var i = 0; i < buttons.length; i++) {
            buttons[i].id += '2';
            this.get_element().appendChild(buttons[i]);
        }
        return (buttons.length > 0 || this.get_countEmptyContainers());
    }
}

BM.AddButtons.registerClass("BM.AddButtons", Sys.UI.Control);

BM.AddButtons.get = function() {
    if (BM.AddButtons._instance == null) {
        BM.AddButtons._instance = BM.AddButtons.find();
    }
    return BM.AddButtons._instance;
}

BM.AddButtons.find = function() {
    var components = Sys.Application.getComponents();
    for (var i = 0; i < components.length; i++) {
        if (BM.AddButtons.isInstanceOfType(components[i])) {
            return components[i];
        }
    }

    return null;
}
